// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const { ccclass, property } = cc._decorator

@ccclass
export default class NewClass extends cc.Component {
  @property(cc.Label)
  label: cc.Label = null

  @property
  text: string = 'hello'

  // 速度
  @property
  v: number = 10

  private timer: number

  private LeftFlag: boolean = false
  private TopFlag: boolean = false

  private BottomFlag: boolean = false
  private RightFlag: boolean = false
  private animation: cc.Animation

  // LIFE-CYCLE CALLBACKS:

  private keyDownFun = (e: any) => {
    const animationState = this.animation.play('run')
    animationState.wrapMode = cc.WrapMode.Loop
    animationState.repeatCount = Infinity

    console.log('ssss')

    console.log(animationState.repeatCount)
    switch (e.keyCode) {
      case cc.macro.KEY.a: {
        this.LeftFlag = true
        break
      }
      case cc.macro.KEY.w: {
        this.TopFlag = true
        break
      }
      case cc.macro.KEY.s: {
        this.BottomFlag = true
        break
      }
      case cc.macro.KEY.d: {
        cc.systemEvent.off(cc.SystemEvent.EventType.KEY_DOWN, this.keyDownFun)

        this.RightFlag = true
        break
      }
      case cc.macro.KEY.f: {
        // 攻击
        this.animation.play()
        console.log(this.animation)
        break
      }
    }
  }

  private keyUpFun = (e: any) => {
    this.animation.pause('run')
    switch (e.keyCode) {
      case cc.macro.KEY.a: {
        this.LeftFlag = false
      }
      case cc.macro.KEY.w: {
        this.TopFlag = false
        break
      }
      case cc.macro.KEY.s: {
        this.BottomFlag = false
        break
      }
      case cc.macro.KEY.d: {
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.keyDownFun)

        this.RightFlag = false
        break
      }
      default: {
      }
    }
  }

  private topMove = (dt: number) => {
    this.node.y += this.v * dt
  }

  private leftMove = (dt: number) => {
    this.node.x -= this.v * dt
  }

  private rightMove = (dt: number) => {
    this.node.x += this.v * dt
  }

  private bottomMove = (dt: number) => {
    this.node.y -= this.v * dt
  }

  onLoad() {
    const node: cc.Node = this.node
    cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.keyDownFun)

    cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.keyUpFun)

    this.animation = this.getComponent(cc.Animation)
  }

  start() {}

  update(dt) {
    if (this.LeftFlag) {
      this.leftMove(dt)
    }
    if (this.TopFlag) {
      this.topMove(dt)
    }
    if (this.RightFlag) {
      this.rightMove(dt)
    }
    if (this.BottomFlag) {
      this.bottomMove(dt)
    }
  }
}
